package com.example.demo.huawei;

import java.util.Stack;

public class MarsCalculator {

    public static int calculate(String expression) {
        String postfix = infixToPostfix(expression);
        return evaluatePostfix(postfix);
    }

    private static String infixToPostfix(String expression) {
        Stack<Character> stack = new Stack<>();
        StringBuilder postfix = new StringBuilder();
        int n = expression.length();

        for (int i = 0; i < n; i++) {
            char ch = expression.charAt(i);
            if (Character.isDigit(ch)) {
                while (i < n && Character.isDigit(expression.charAt(i))) {
                    postfix.append(expression.charAt(i));
                    i++;
                }
                postfix.append(' ');
                i--; // 因为for循环还会i++
            } else if (ch == '#') {
                while (!stack.isEmpty() && stack.peek() == '#') {
                    postfix.append(stack.pop()).append(' ');
                }
                stack.push(ch);
            } else if (ch == '$') {
                while (!stack.isEmpty() && (stack.peek() == '#' || stack.peek() == '$')) {
                    postfix.append(stack.pop()).append(' ');
                }
                stack.push(ch);
            }
        }

        while (!stack.isEmpty()) {
            postfix.append(stack.pop()).append(' ');
        }

        return postfix.toString().trim();
    }

    private static int evaluatePostfix(String postfix) {
        Stack<Integer> stack = new Stack<>();
        String[] tokens = postfix.split(" ");

        for (String token : tokens) {
            if (token.equals("#") || token.equals("$")) {
                int y = stack.pop();
                int x = stack.pop();
                if (token.equals("#")) {
                    stack.push(2 * x + 3 * y + 4);
                } else if (token.equals("$")) {
                    stack.push(3 * x + y + 2);
                }
            } else {
                stack.push(Integer.parseInt(token));
            }
        }

        return stack.pop();
    }

    public static void main(String[] args) {
        System.out.println(calculate("7#6$5#12")); // 226
        System.out.println(calculate("1234#5#67$8")); // 根据输入计算并输出结果
    }
}
